﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using CommonExtensions.ExpressionExtensions.OfFunc;
using CommonExtensions.ObjectExtensions;
using CommonExtensions.StringExtensions;

namespace CommonExtensions.IDataErrorInfoExtensions.Testing
{
    public static class Extensions
    {
        public static void AssertPropertyValid<T>(this T obj, Expression<Func<T,object>> propertyExpression)
            where T : IDataErrorInfo
        {
            obj.AssertPropertyHelper(propertyExpression, true);
        }

        public static void AssertPropertyInvalid<T>(this T obj, Expression<Func<T, object>> propertyExpression)
            where T : IDataErrorInfo
        {
            obj.AssertPropertyHelper(propertyExpression, false);
        }

        private static void AssertPropertyHelper<T>(this T obj, Expression<Func<T, object>> propertyExpression, 
            bool shouldBeValid)
            where T : IDataErrorInfo
        {
            if (obj.IsNull())
                throw new ArgumentNullException("obj");
            if (propertyExpression.IsNull())
                throw new ArgumentNullException("propertyExpression");

            string propertyName = propertyExpression.GetPropertyName();
            string errors = obj[propertyName];

            if(shouldBeValid)
            {
                if (!errors.IsBlank())
                {
                    throw new AssertFailedException(string.Format("{0} has the following error(s): {1}", propertyName,
                                                                  errors));
                }   
            }
            else
            {
                if (errors.IsBlank())
                {
                    throw new AssertFailedException(string.Format("{0} has no errors", propertyName));
                }   
            }
        }
    }
}